package com.cci.kangdao.service.impl;

import com.cci.kangdao.dao.FileTDao;
import com.cci.kangdao.dao.model.FileT;
import com.cci.kangdao.entity.FileEntity;
import com.cci.kangdao.service.FileUploadService;
import com.cci.kangdao.utilTool.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author William Du
 * @date 2020/2/6
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private FileTDao fileTDao;

    @Override
    public void uploadFileToAzure(HttpServletRequest request) {
        HttpServletResponse response = RequestContextHolder.getResponse();
        List<FileEntity> fileEntityList = uploadFilesToAzure(request);
        List<Map<String,Object>> responseList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(fileEntityList)){
            for(FileEntity fileEntity: fileEntityList){
                Map<String,Object> fileMap = new HashMap<>(3);
                fileMap.put("id",String.valueOf(fileEntity.getId()));
                fileMap.put("fileName",fileEntity.getFileName());
                fileMap.put("fileUrl",fileEntity.getFileUrl());
                responseList.add(fileMap);
            }
        }
        ParameterTool.writeSuccessResponse(response,responseList);
    }

    @Override
    public List<FileEntity> uploadFilesToAzure(HttpServletRequest request) {
        List<FileEntity> fileEntityList = new ArrayList<>();
        String uploadPath = PropertiesUtil.getProperties("projectconfig.properties", "upload").trim();
        String basePath = request.getSession().getServletContext().getRealPath(uploadPath);
        List<FileEntity> tempFileList = FileUploadUtils.uploadMultiFile(request,basePath);
        if(CollectionUtils.isNotEmpty(tempFileList)){
            fileEntityList = FileUploadUtils.uploadAzureFile(tempFileList);
            if(CollectionUtils.isNotEmpty(fileEntityList)){
                for(FileEntity fileEntity: fileEntityList){
                    FileT fileT = BeanUtils.convert(fileEntity,FileT.class);
                    fileTDao.insertSelective(fileT);
                    fileEntity.setId(fileT.getId());
                }
            }
            FileUploadUtils.clearFiles(tempFileList);
        }

        return fileEntityList;
    }


}
